package com.test.web.nettyserver;

import com.test.web.controller.TestService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
@ChannelHandler.Sharable
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private TestService testService;

    @Autowired
    private DispatcherServlet dispatcherServlet;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        try {
        //Discard the received data silently
        //ByteBuf是一个引用计数对象实现ReferenceCounted，他就是在有对象引用的时候计数+1，无的时候计数-1，当为0对象释放内存
        FullHttpRequest request = (FullHttpRequest)msg;
        System.out.println("discardServerHandler111");
        HttpMethod method = request.method();
        String methodName = method.name();
        log.info("uri:{}",request.uri());
        log.info("methodName:{}",methodName);
        log.info("content:"+request.content().toString());
        String res = testService.responseTest();
        System.out.println(""+res);

        log.info(dispatcherServlet.getServletName());
        //用dispatcherServlet 处理请求




        ByteBuf resByteBuf = Unpooled.copiedBuffer(res, CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK
                , resByteBuf);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }



}
